<!--
 * @Author: zjf
 * @Date: 2022-09-21 11:40:41
 * @LastEditors: zjf
 * @LastEditTime: 2023-12-16 20:00:20
 * @Description: 项目详情
-->
<template >
  <div class="index-page" v-loading="loading">
    <div class="index-grid">
      <!-- 项目全生命周期 -->
      <el-card class="full-cycle card card-aside" header="项目全生命周期">
        <div class="card-main cycle-content">
          <span class="project-Name" @click="selectProject('BasicInformation')">基本信息</span>
          <span class="project-Name" @click="selectProject('ProgressInformation')">进度信息</span>
          <span class="project-Name" @click="selectProject('InvestmentsAndPayments')">投资和纳统</span>
          <span class="project-Name list-stage" @click="selectProject('StageInformation')">
            阶段信息
            <span class="deployment" v-if="!isShowStage" @click="isShowStage = true">
              展开
              <i class="el-icon-arrow-down"></i>
            </span>
            <span class="deployment" v-else @click="isShowStage = false">
              收起
              <i class="el-icon-arrow-up"></i>
            </span>
          </span>
          <template v-if="isShowStage">
            <template v-for="stage in  fullCycleData.stageList">
              <div class="fullCycle" :key="stage.stageCode">
                <i class="cycle"></i>
                <span class="fullCycle-name">{{stage.stageName}}</span>
                <template v-for="business in  stage.businessList">
                  <span v-if="business.bizId" class="fullCycle-busin" :key="business.businessCode + business.bizId"
                    :class="[{active: business.bizId ===  selBusinessId},{effect:business.bizId}]"
                    @click="selectBusiness(business)">{{business.businessName}}</span>
                </template>
              </div>
            </template>
          </template>
        </div>
      </el-card>
      <div class="detail-and-map">
        <el-card class="business-detail card">
          <div slot="header" class="detail-header">
            <span>{{ detailFormTitle }}</span>

            <span v-if="isShowStageList && hasEdit">
              <span @click="handleCreateStage"><i :class="'el-icon-edit'" style="margin-right:4px;"></i>新增阶段</span>
            </span>
            <template v-else>
              <span @click="changeFromEdit" v-if="hasEdit">
                <i :class="isEdit?'el-icon-s-order':'el-icon-edit'" style="margin-right:4px;"></i>
                {{isEdit?'保存':'编辑'}}
              </span>
            </template>
          </div>
          <div class="card-main detail-cardmain">
            <template v-if="isShowStageList">
              <l-table ref="mainTable" :loading="tableLoading"
                :columns="[{label:'阶段',prop:'stageName'},{label:'子阶段',prop:'businessName'}]"
                :dataSource="existingPhasesList" :isPage="false">
                <l-table-btns v-if="hasEdit" :btns="[{ prop: 'PhasesDelete', label: '删除' }]"
                  @click="lr_handleTableBtnClick"></l-table-btns>
              </l-table>
            </template>
            <template v-else>
              <el-form :model="formData" :rules="formConfig.rules || {}" size="mini" labelPosition="right"
                :labelWidth="`${formConfig.width  || 110}px`" ref="form">
                <l-custom-form ref="CustomForm" :disabled="!isEdit" :span="24" :columns="formConfig.formColmuns">
                  <template #dividingLine1>
                    <el-divider content-position="right" class="dividingLine"
                      @click="handleOpenInves('tab1')">完成投资明细</el-divider>
                  </template>
                  <template #dividingLine2>
                    <el-divider content-position="right" class="dividingLine"
                      @click="handleOpenInves('tab2')">纳统投资明细</el-divider>
                  </template>
                  <template #dividingLine3>
                    <el-divider content-position="right" class="dividingLine"
                      @click="handleOpenInves('tab3')">合同明细</el-divider>
                  </template>
                  <template #dividingLine4>
                    <el-divider content-position="right" class="dividingLine"
                      @click="handleOpenInves('tab4')">申请明细</el-divider>
                  </template>
                  <template #dividingLine5>
                    <el-divider content-position="right" class="dividingLine"
                      @click="handleOpenInves('tab5')">支付明细</el-divider>
                  </template>
                  <template v-if="isEdit&& detailFormTitle == '进度信息'" #other>
                    <el-button type="primary" size="mini" @click="handleOpenProgress">施工阶段进展</el-button>
                  </template>
                </l-custom-form>
              </el-form>
            </template>
          </div>
        </el-card>
      </div>
      <!-- 文件资料 -->
      <el-card class="electronic-file card card-aside">
        <div slot="header"> {{detailFormTitle == '基本信息'?'项目红线':'文件资料' }}</div>
        <div class="card-main file-project">
          <MapIndex v-if="detailFormTitle == '基本信息' && projectId" ref="mapIndex" :projectId="projectId"
            :hasEdit="hasEdit"> </MapIndex>
          <FileManagement v-if="detailFormTitle !== '基本信息'" ref="fileManagement" :businessId="selBusinessId"
            :projectId="projectId" :disabled="!hasEdit">
          </FileManagement>
        </div>
      </el-card>

    </div>

    <InvesDialogForm ref="InvesDialogForm"></InvesDialogForm>

    <ProgressDialogForm ref="ProgressDialogForm" formTitle="施工阶段进展"></ProgressDialogForm>

    <l-stage-add ref="StageAdd"></l-stage-add>

  </div>
</template>

<script>
import stageColumns from "../../js/columns";
import projectColumns from "../../../projectManagement/js/columns";
import FileManagement from "@/core/components/file-management/indexDetail.vue";
// import FileManagement from "@/core/components/file-management/fileTree.vue";

import MapIndex from "./mapIndex.vue"
import InvesDialogForm from '../../../projectManagement/views/InvestmentsAndPayments/DialogForm.vue'
import ProgressDialogForm from '../../../projectManagement/views/ProgressInformation/DialogForm.vue'


export default {
  components: {
    FileManagement,
    MapIndex,
    InvesDialogForm,
    ProgressDialogForm
  },
  props: {
    businessId: {
      type: String,
      default: "",
    },
    businessCode: {
      type: String,
      default: "",
    },
    hasEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: true,

      isShowStage: true, // 是否展开阶段列表
      projectId: "",
      projectInfo: {},//当前项目数据
      progressId: "", // 当前项目进度id
      fullCycleData: { stageList: [] },//生命周期数据
      basicInfoType: "",

      formConfig: [],     // 表单配置信息
      formData: {}, // 表单数据

      selBusinessId: '',//当前业务id
      selBusinessCode: '',//当前业务code
      selBusinessInfo: {},//当前业务数据
      businessName: "",//当前业务name

      detailFormTitle: "基本信息", // 详情表单名称

      isEdit: false,

      tableLoading: true,
      existingPhasesList: []

    };
  },
  mounted() {
  },
  computed: {
    stageList() {
      const data = this.lr_DataSource('businessStage')
      return data || []
    },
    isShowStageList() { // 当前处于阶段信息模块
      if (this.basicInfoType == 'StageInformation' && this.formConfig.name && this.formConfig.name == '阶段信息') {
        return true
      }
      return false
    },
  },
  methods: {
    init(origin) {
      // 加载初始化信息
      this.getProjectData(origin.projectId)
    },
    /** 通过项目id获取生命周期 项目详情 项目进度列表 项目文件树 */
    async getProjectData(projectId) {
      this.projectId = projectId

      // 项目基本信息
      const data = await this.$awaitWraper(window.$crud("project").get(projectId))
      this.projectInfo = data || {}

      await this.loadProgressList() // 获取项目进度列表
      await this.loadFullCycleData() // 生命周期接口
      await this.loadListOfExistingPhases() // 获取已有阶段列表

      this.selectProject('BasicInformation') // 初始化表单信息
      // this.loadProjectFolder() // 加载文件树
    },
    /** 获取生命周期 */
    async loadFullCycleData() {
      const result = await this.$awaitWraper(window.$crud("project/stage/all").get(this.projectId)).catch(() => null)
      this.fullCycleData = result || { stageList: [] }
      this.loading = false
    },
    /** 获取项目进度列表 */
    async loadProgressList() {
      const result = await this.$awaitWraper(window.$crud("project/progress/list").getInfo({ projectId: this.projectId })).catch(() => [])
      const progressInfo = result[0] ?? {}
      this.progressId = progressInfo.id || ""
    },
    /** 获取已有阶段列表 */
    async loadListOfExistingPhases() {
      this.tableLoading = true
      let data = []
      this.fullCycleData.stageList.forEach(t => {
        if (t.businessList && t.businessList.length) {
          t.businessList.forEach(b => {
            data.push({
              stageName: t.stageName,
              stageCode: t.stageCode,
              businessName: b.businessName,
              id: b.bizId,
              businessCode: b.businessCode,
              businessId: b.bizId,
            })
          })
        }
      })
      this.existingPhasesList = data.filter(t => t.businessId)
      this.tableLoading = false
    },

    /** 阶段删除 */
    handlePhasesDelete($index, row) {
      if (row.businessCode) {
        const stage = this.setBusinessData(row.businessCode);
        const stageConfig = stageColumns[stage.route_code]

        this.$confirm(this.$t('是否删除该阶段数据?'), this.$t('提示'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(async () => {
          await stageConfig.api.remove(row.id)
          this.$message({
            type: 'success',
            message: this.$t('删除成功!')
          })
          await this.loadFullCycleData() // 生命周期接口
          await this.loadListOfExistingPhases() // 获取已有阶段列表
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('已取消删除!')
          })
        })
      }
    },

    /** 阶段生命周期点击事件 */
    async selectBusiness(work) {
      this.basicInfoType = ''
      if (!this.isEdit) {
        if (work.bizId) {
          //获取生命周期点击时获得的业务id code
          this.selBusinessId = work.bizId //控制高亮
          work.businessId = work.bizId
          work.name = work.businessName
          this.selBusinessCode = work.businessCode
          this.businessName = work.businessName
          this.detailFormTitle = work.businessName

          //获取业务信息
          this.setFormConfig()
          // 加载文件树
          await this.$refs.fileManagement.init(work)
        }
      } else {
        this.$message({
          type: 'warning',
          message: this.$t('当前表单未保存!')
        })
      }
    },
    /** 基本信息 进度信息 投资纳统 阶段信息 点击事件 */
    async selectProject(code) {
      this.basicInfoType = code
      if (!this.isEdit) {
        this.formConfig = projectColumns[code]
        this.formData = this.formConfig.formData
        this.detailFormTitle = this.formConfig.name
        if (code == 'ProgressInformation') {
          this.selBusinessId = this.progressId
        }
        else if (code == 'StageInformation') {
          return
        }
        else {
          this.selBusinessId = this.projectId
        }
        this.$nextTick(() => {
          this.$refs.CustomForm.init()
          this.loadFormData(this.selBusinessId)
        })
        // 加载文件树
        // this.loadProjectFolder()
      } else {
        this.$message({
          type: 'warning',
          message: this.$t('当前表单未保存!')
        })
      }
    },


    /** 获取项目文件树 */
    async loadProjectFolder() {
      this.$refs.fileManagement.loadProjectFolder()
    },

    //#region 加载表单信息
    setFormConfig() {
      const stage = this.setBusinessData(this.selBusinessCode);
      this.formConfig = stageColumns[stage.route_code]
      this.formData = this.formConfig.formData
      this.$nextTick(() => {
        this.$refs.CustomForm.init()
        this.loadFormData(this.selBusinessId)
      })
    },
    /** 根据阶段 business_code 获取阶段信息 */
    setBusinessData(businessCode) {
      const stage = this.stageList.find((t) => t.business_code == businessCode);
      return stage
    },
    /** 加载项目阶段信息   初始化表单 */
    async loadFormData(selBusinessId) {
      const data = await this.$awaitWraper(this.formConfig.api.get(selBusinessId))
      this.selBusinessInfo = data || {}
      if (data) {
        for (const key in this.formData) {
          if (this.projectInfo[key]) {
            this.formData[key] = this.projectInfo[key] || "";
          }
          if (Object.prototype.hasOwnProperty.call(data, key)) {
            if (typeof data[key] === 'boolean') {
              data[key] = data[key].toString();
            }
          }
          if (data.projectInvestmentPayment && data.projectInvestmentPayment.length > 0) {
            this.formData[key] = data.projectInvestmentPayment[0][key] || 0
          }
          this.formData[key] = data[key] || this.formData[key];
        }
        this.$refs.CustomForm.formData = this.formData
      }
    },

    /** 表单编辑保存 状态切换 */
    changeFromEdit() {
      if (this.isEdit) {// 点击保存
        this.$confirm(this.$t('是否保存更改?'), this.$t('提示'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'success'
        }).then(() => {
          this.handleSaveForm()
        }).catch(() => {
          this.$message({ type: 'info', message: this.$t('已取消!') })
        })
      } else { // 点击编辑
        if (this.basicInfoType == 'InvestmentsAndPayments') {
          this.$refs.InvesDialogForm.open({ id: this.projectId });
          return
        }
        // if (this.basicInfoType == 'ProgressInformation') {
        //   this.$refs.ProgressDialogForm.open({ id: this.projectId });
        //   return
        // }
      }
      this.isEdit = !this.isEdit
    },
    /** 打开投资和纳统计表单 */
    handleOpenInves(activeName) {
      this.$refs.InvesDialogForm.open({ id: this.projectId, activeName: activeName });
    },

    /** 打开施工进展表单 */
    handleOpenProgress() {
      this.$refs.ProgressDialogForm.open({ id: this.projectId, activeName: 'tab1' });
    },

    /** 表单编辑、保存事件 */
    async handleSaveForm() {
      let postData = this.$refs.CustomForm.formData
      const res = await this.$awaitWraper(this.formConfig.api.update(this.selBusinessId, postData))
      if (res) {
        this.$message({ type: 'success', message: '提交成功' })
      }
    },
    //#endregion

    /** 新增阶段 */
    handleCreateStage() {
      this.$refs.StageAdd.open({
        projectInfo: {
          id: this.projectId,
          projectId: this.projectId,
          projectName: this.projectInfo.projectName,
        }
      })
    },

  }
}
</script>

<style lang="scss" scoped>
@import "./detail.scss";
.list-stage {
  display: flex;
  flex-direction: row;
  justify-content: space-between;

  .deployment {
    font-size: 14px;
  }
}
</style>